import cv2 as cv
from ultralytics import YOLO
# Load a model
model = YOLO('yolov8n.pt')
cap = cv.VideoCapture(0)
filepath = "D:/python/v8_mine/照片/标准/"
epoch = 0
while(1):
    ret, frame = cap.read()
    # Run batched inference on a list of images
    result = model(frame)  # return a list of Results objects
    result = result[0]
    # Process results list
    boxes = result.boxes  # Boxes object for bounding box outputs
    masks = result.masks  # Masks object for segmentation masks outputs
    keypoints = result.keypoints  # Keypoints object for pose outputs
    probs = result.probs  # Probs object for classification outputs

    class_ids = boxes.cls.cpu().numpy().astype(int)
    if 67 in class_ids:  # 检测到手机
        # 遍历手机边界框，计算并输出中心位置
        for phone_box in boxes:
            xyxy_tensor = phone_box.xyxy[0]  # 提取第一个边界框的xyxy坐标tensor
            xyxy_coords = xyxy_tensor.cpu().numpy()  # 将tensor转换为NumPy数组，并确保它在CPU上

            # 分解坐标并保存到变量中
            x1, y1, x2, y2 = xyxy_coords

            # 现在您可以使用x1, y1, x2, y2进行后续操作
            print(f"x1: {x1}, y1: {y1}, x2: {x2}, y2: {y2}")

            # 如果您需要将这些坐标保存到某个数据结构（如列表），可以这样做：
            # coords_list.append((x1, y1, x2, y2))
        result.save(filename='./image_cellphone/result_' + str(epoch) + '.jpg')  # 保存
        epoch = epoch + 1
        print("检测到手机，已经保存")

    image = result.plot()
    # result.show()  # display to screen
    # result.save(filename='result.jpg')  # save to disk
    # image = cv.imread("result.jpg")

    cv.imshow("image", image)  # 显示图片
    k = cv.waitKey(1)  # 等待按键
    if k == ord("q"):
        break